import {
	msg
} from './util.js';

import JSEncrypt from 'jsencrypt';

let BASE_URL = 'http://192.168.88.237:8788/api';
// let BASE_URL = '/kkk';

const CryptoJS = require('crypto-js');
// 1.导入
import store from '@/store';
import MD5 from 'md5';
const AES = require('./aes'); // 假设 aes.js 在同一目录下

function generateUUID() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random() * 16 | 0,
			v = c === 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
}

function getRandomString(length) {
	const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	const charactersLength = characters.length;
	let result = '';

	for (let i = 0; i < length; i++) {
		const randomIndex = Math.floor(Math.random() * charactersLength);
		result += characters[randomIndex];
	}

	return result;
}

function http_build_query(data, prefix = null) {

	const queryParts = [];

	for (const [key, value] of Object.entries(data)) {
		// 处理数组和对象
		if (typeof value === "object" && value !== null) {
			// 判断是否为空数组或空对象
			if (Array.isArray(value) && value.length === 0) {
				continue;
			}
			if (Object.prototype.toString.call(val[k]) === '[object Object]' && Object.keys(value).length === 0) {
				continue;
			}
			const newPrefix = prefix ? `${prefix}[${encodeURIComponent(key)}]` : encodeURIComponent(key);
			queryParts.push(http_build_query(value, newPrefix));
		}
		// 处理 true 值
		else if (value === true) {
			const encodedKey = encodeURIComponent(prefix ? `${prefix}[${encodeURIComponent(key)}]` : encodeURIComponent(key));
			queryParts.push(`${encodedKey}=1`);
		}
		// 处理 false 值
		else if (value === false) {
			const encodedKey = encodeURIComponent(prefix ? `${prefix}[${encodeURIComponent(key)}]` : encodeURIComponent(key));
			queryParts.push(`${encodedKey}=0`);
			return;
		}
		// 处理 null 值
		else if (value === null) {
			// 空值直接跳过
			continue;
			// const encodedKey = encodeURIComponent(prefix ? `${prefix}[${encodeURIComponent(key)}]` : encodeURIComponent(key));
			// queryParts.push(`${encodedKey}=`); // 加上等号
		}
		// 处理普通值
		else {
			const encodedKey = encodeURIComponent(prefix ? `${prefix}[${encodeURIComponent(key)}]` : encodeURIComponent(key));
			const encodedValue = encodeURI(value);
			queryParts.push(`${encodedKey}=${encodedValue}`);
		}
	}

	return queryParts.join('&');
}

function sortData(data, sortOrder = "asc") {
	const compareFunction = (a, b) => {
		if (a === b) {
			return 0;
		}
		return sortOrder === "desc" ? (a > b ? -1 : 1) : (a < b ? -1 : 1);
	};

	if (Array.isArray(data)) {
		return Object.keys(data).sort(compareFunction).map((value) => {
			value = data[value];
			return typeof value === "object" && value !== null ?
				sortData(value, sortOrder) :
				value
		});
	}

	if (typeof data === "object" && data !== null) {
		const sortedObject = {};
		const sortedKeys = Object.keys(data).sort(compareFunction);

		for (const key of sortedKeys) {
			sortedObject[key] =
				typeof data[key] === "object" && data[key] !== null ?
				sortData(data[key], sortOrder) :
				data[key];
		}

		return sortedObject;
	}

	return data;
}


//拼接参数
function splicingParameter(data) {
	let signParams = {};
	if (data) {
		signParams = data;
	}
	const appId = '1000000001';
	let appKey = MD5(generateUUID());
	let timestamp = Math.round(new Date().getTime() / 1000).toString();
	let nonceStr = getRandomString(10);
	let signStr = ''
	signParams['appId'] = appId;
	signParams['timestamp'] = timestamp;
	signParams['nonceStr'] = nonceStr;

	let signParamsKey = sortData(signParams);

	signStr = http_build_query(signParamsKey)



	let paramStr = decodeURI(signStr) + appKey;




	const signature = CryptoJS.SHA256(paramStr).toString();


	var per = {};

	per.appId = appId;
	per.appKey = appKey;
	per.timestamp = timestamp;
	per.nonceStr = nonceStr;
	per.signature = signature;

	return per;
}




//解密内容
function decryptAES(encrypted, keyHex) {
	const aes = AES.fromHex(keyHex); // 从十六进制生成 AES 对象
	const decryptedText = aes.decrypt(encrypted); // 解密密文
	console.log("解密内容：", decryptedText); // 打印解密后的明文
	return decryptedText;
}

//加密内容
function encryptAES(plaintext, keyHex) {

	const aes = AES.fromHex(keyHex); // 从十六进制生成 AES 对象
	console.log('加密内容函数aaaaaaa', plaintext);
	console.log('加密内容函数bbbbbbb-key', keyHex);

	// const plaintextssss = '你好，二蛋！';
	const encrypted = aes.encrypt(plaintext);
	console.log("加密内容encryptAESencryptAESencryptAES：", encrypted);
	return encrypted;
}


const request = (options = {}) => {

	options.header = options.header || {};
	var per = {};

	//生成请求头
	per = splicingParameter(options.data);

	// 这里不能删除加密用的+++++++++++++++++++++++++
	// if (!options.data) {
	// 	options.data = [];
	// }

	// const jsonString = JSON.stringify(options.data);
	// var datajm = encryptAES(jsonString, per.appKey);
	// options.data = JSON.stringify(datajm);
	// 这里不能删除加密用的-------------------------

	var publicKeyPem = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4tWQnbBpgNzpXMYWGvrj
Y22qztV8BpXFgj4hUR9aVSXKyiesNVGvD052JawgtvAAfruRNIScvMwzoe4IcrOL
OTD7DR2Gd4nIyAnwGYvPsslYo1bOhJhZNp4CsbMREEzQDPvMQQHZKbxM7U0/GRlv
m2/bwHR4T0ywE+hd9N5TS9F+eC08oTRokG87rlbhQEmOOl/mZK6PTSqQUE8X0gbO
H+ccg2GcYsys3rUpK67RRW1cYns0JjXUKnTOIUY7YeD/P8L7jhVYPz2lC2C0U7x0
Y1d0QDyevuH6LP5t0dX9IuAzzs5B5YG47BP2P/Ga7hUUVgsdTeQKiKm5ujf8QkyY
VwIDAQAB
-----END PUBLIC KEY-----
	`;

	const encrypt = new JSEncrypt();
	encrypt.setPublicKey(publicKeyPem);
	const encrypted = encrypt.encrypt(per.appKey);


	options.header['appId'] = per.appId;
	options.header['appKey'] = encrypted;
	options.header['timestamp'] = per.timestamp;
	options.header['nonceStr'] = per.nonceStr;
	options.header['signature'] = per.signature;


	console.log('requeset.js请求头111111111', options.header);


	// 判断是否有访问令牌
	// const access_token = store.state.access_token;

	const access_token = uni.getStorageSync('access_token_user');

	if (access_token) {
		// oauth2协议
		options.header['Authorization'] = `Bearer ${access_token}`;
		options.header['content-type'] = 'application/x-www-form-urlencoded';
		// options.header = {
		// 	'Authorization': `Bearer ${access_token}`,
		// 	'content-type': 'application/x-www-form-urlencoded'
		// };
	}

	// 短信验证码也要放行
	const whileList = ['/system/sms/code', '/auth/login', '/auth/login/provider', '/auth/user/mobile'];

	// resolve 正常响应，reject异常响应
	return new Promise((resolve, reject) => {
		if (options.isLogin && !openid) {
			//跳转到登录页
			return uni.navigateTo({
				url: '/pages/auth/login'
			});
		}
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			timeout: 8000, // 8秒超时时间，单位ms
			header: options.header || {},
			success: (res) => {
				if (res.data.code == 11) {
					// 你的 RSA 私钥（PEM 格式）
					const privateKeyPem = `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA7JtMYWkJxqXGPYgao+kX7IYJaq0+OVQpMbvac5zrYsUetcbI
df9WBuMys+fCpXQQjuTpqV41BY5vlg7DNG6N5L4CzF2g75fqxq9x017EZIKjrLuK
qac5dgzZ/phY6itX+lsK1g1u+eGi20UeC0nXW4WP9vnRojiba+7lkn7F4syuMWcH
ffkveQ0NZ4YNEjLNgIk/viZCbjvgfSg4pMmrcd4m6jDlqON1xYbqqM8OEDoa7MvF
hmA2U4WPrZ5BXzsi9GUoGQXWzeT6AssISEvxDqmA0IyKn2Lar5PJOAKWYtI8+vKI
lTjcsxJYDSUiIHRtszzHz2YVMkZGIoyjGRhpKQIDAQABAoIBABbfdnVOQa8t9Gmb
YDPrQzBOztc8szC4lZjkt5wIlerA8pSRCGz7x5W33f1tULBM9ZLSx1HjtQ159QiV
GcLWUypDQiL+hCHVVlFpwX+1ABhVVrxKjv+Slmf2mxZVJPdSRFmD9pq1xr4qVWOM
HXjq5QJIeZ/fC6h6f2/iMthEIB4qCq0TpWM8bNZa5k2xQdz63Cq8y0s/mphK7x+w
tkjBZ8XScpK/Vrb0hbBpWKkCVDdmQ1UIQJ02/t1+RXZHcy5t/1j4LDWu+apeVTE8
FgmpwRxBe00/wrrdv+Pce/t8v4MdjU//sTijTJKZteZJ8HDB9gpTw90ijdR+nqUt
opUX99cCgYEA/Kx4fziGxp2XvmromnIbryS+n0Ojaj55MJ3UqpCrpUhoUVMxTcS6
iK1GdO7D11wBXIAGIAzeZKIC6q52m4c75iPVdE3KsnGm8Mmc56AL7drdPg7mQpat
D9POYO/ivGNiP/5fus4qGtvXQokBdAMPfrNVPH6+HCqwwahN+c+SyVcCgYEA77iu
L2uo1c3U2FPFXityIUORpsKaC2gq9hMs7T0p0mQfaFIgupGosB92isO4xhmarn4V
SHqNoo8OwiYCjjsHJWuVNe5guhNOrmzzZ6SFUe93Lldqmcr9KVN7jJvmRXI2KxwC
lN7v/7AlQ57vlgEDHaiIHWQn7HYE38krQVm+UX8CgYBqUEtXBDq5IR/y79q0+WQq
mmRWcMg2cNjfGtmbdsmx/rhd14o8NZVi4r1tf/UJDV5JRFjPbXq5ju15PzUKlakf
WV571CuAT4+1aq9JSi8awmcqsGw0AmAI8863PNgC+jIhyO8Qk6RlrrBw/2KMJKmF
XwFzNcTZ5yB+K0m73ZneewKBgDhuvXKkYYaTgfu7HMdiauexxGQBg8oTp6luMjFX
KLVCpLImQ1YoXBG6FmnsUV8xP9y8Cb6aOyV9j/fcgtWAx9njTaj4iQTE7szZESPg
8xGq0d+y7IFv69ECuh8LxFWs4VucqG7rXIxQpzUYAUbKzjT5K7HflhZwYg1cijZE
Li15AoGBAJ8WIi3miqEUaLXFQRgidLCDqqslo3SbxwZmLSJ3LzE46MR3Xsu6c1yI
4mFz8r3LOiydshUl9JZs53mtkrX6H4aL4BRnHtrWF35rle+W5qmEi+B3SeIkSd12
6ZVRHSByG/MjHID1DFw5hkcJbGboBje2HR7UxC4DOH8Pc4b9NH6S
-----END RSA PRIVATE KEY-----`;

					// 获取的key
					const encryptedKey = res.data.key;

					// 创建 JSEncrypt 实例
					const encryptor = new JSEncrypt();
					encryptor.setPrivateKey(privateKeyPem);

					// 解密key
					const key = encryptor.decrypt(encryptedKey);

					//解密内容
					var data = decryptAES(res.data.data, key);

					console.log('hahahha', data);

					res.data.data = data;

				}

				resolve(res.data);
			},
			fail: (err) => {
				console.log('请求接request.js口失败', err)
				msg('请求接request.js口失败');
				reject(err);
			}
		});
	});
};

// 导出
export default request;